<template>
  <el-tag
    v-for="(tag, index) in dynamicTags"
    :key="index"
    class="el-tag tag-bottom"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
  >
    {{ tag }}
  </el-tag>
  <el-input
    v-if="inputVisible"
    ref="InputRef"
    v-model="inputValue"
    class="input-new-tag tag-bottom"
    @keyup.enter="handleInputConfirm"
    @blur="handleInputConfirm"
  >
  </el-input>
  <el-button v-else class="button-new-tag tag-bottom" @click="showInput">
    + New Tag
  </el-button>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElInput } from 'element-plus'
const props = defineProps({
  dynamicTags: {
    type: Array,
    default: [],
  },
})
const emit = defineEmits(['changeDynamicTag'])
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
// 点击关闭当前标签
const handleClose = (tag: any) => {
  let dynamicTags = JSON.parse(JSON.stringify(props.dynamicTags))
  dynamicTags.splice(dynamicTags.indexOf(tag), 1)
  emit('changeDynamicTag', dynamicTags)
}
// 点击button 按钮时显示input输入框和自动聚焦
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
// input 输入框失去焦点时触发
const handleInputConfirm = () => {
  if (inputValue.value) {
    let dynamicTags = JSON.parse(JSON.stringify(props.dynamicTags))
    dynamicTags.push(inputValue.value)
    emit('changeDynamicTag', dynamicTags)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>
<style scoped lang="scss">
.el-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
}
.tag-bottom {
  margin-bottom: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
